use axum::{Json, Router};
use axum::response::IntoResponse;
use axum::routing::{post};
use serde::Deserialize;
use crate::error::LoginError;
use crate::token::Token;
use crate::service::login as user_login;

#[derive(Debug, Deserialize)]
pub struct LoginParam {
    username: String,
    password: String,
}

pub fn user_router() -> anyhow::Result<Router> {
    let router = Router::new()
        .route("/login", post(login));

    Ok(router)
}

pub async fn login(Json(param): Json<LoginParam>) -> Result<Json<Token>, LoginError> {
    let token = user_login(&param.username, &param.password).await
        .map_err(|_| LoginError::UserOrPassword)?;

    Ok(Json(token))
}